/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ep.m001.ui.views;

import com.vaadin.data.Item;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.terminal.gwt.server.WebApplicationContext;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Component;
import com.vaadin.ui.ComponentContainer;
import com.vaadin.ui.Field;
import com.vaadin.ui.Form;
import com.vaadin.ui.FormFieldFactory;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.OptionGroup;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window.Notification;
import ep.libs.implementations.AbstractModule;
import ep.libs.implementations.AbstractView;
import ep.m001.module.M001Module;
import ep.m001.ui.controllers.M001Controller;
import ep.m002.module.M002Module;
import java.util.Collection;

/**
 *
 * @author Spyros
 */
public class RegisterView extends AbstractView {

    // <editor-fold defaultstate="collapsed" desc="captions">
    public static final String USERNAME = "Όνομα χρήστη";
    public static final String PASSWORD = "Κωδικός Πρόσβασης";
    public static final String TYPE = "Κατηγορία";
    public static final String DOCTOR_CAPTION = "Γιατρός";
    public static final String PHARMACIST_CAPTION = "Φαρμακοποιός";
    public static final String DEP_CAPTION = "Διαχειριστής";
    public static final String FIRSTNAME_CAPTION = "Όνομα";
    public static final String SURNAME_CAPTION = "Επώνυμο";
    public static final String FATHERNAME_CAPTION = "Όνομα Πατρός";
    public static final String MOTHERNAME_CAPTION = "Όνομα Μητρός";
    public static final String DATEOFBIRTH_CAPTION = "Ημ. Γέννησης";
    public static final String AMKA_CAPTION = "ΑΜΚΑ";
    public static final String AMETAA_CAPTION = "ΑΜΕΤΑΑ";
    public static final String DATEAMETAA_CAPTION = "Ημ. ΑΜΕΤΑΑ";
    public static final String AFM_CAPTION = "ΑΦΜ";
    public static final String SPECIALTY_CAPTION = "Ιδιότητα";
    public static final String CLUB_CAPTION = "Σύλλογος";
    public static final String LICENCENO_CAPTION = "Αρ.Αδείας";
    public static final String PHONE_CAPTION = "Τηλέφωνο";
    public static final String MOB_CAPTION = "Κινητό";
    public static final String EMAIL_CAPTION = "Email";
    public static final String ADDRESS_CAPTION = "Διεύθυνση";
    public static final String TK_CAPTION = "ΤΚ";
    public static final String CITY_CAPTION = "Πόλη";
    public static final String T004INSURANCES_CAPTION = "Ασφαλιστικά Ταμεία";
    public static final String CANCEL_CAPTION = "Άκυρο";
    public static final String SIGNUP_CAPTION = "Η εγγραφή ολοκληρώθηκε.";
    // </editor-fold>
    private Boolean isEdit;
    private Boolean isDoctor;
    private Boolean isPharmacist;
    private Boolean isDep;
    private M001Controller controller = new M001Controller();
    private String[] registerVisibleFields;
    private String[] doctorVisibleFields;
    private String[] pharmacistVisibleFields;
    private Form registerForm;
    private Form doctorForm;
    private Form pharmacistForm;
    private Button registerButton;
    public Button cancelButton;

    public RegisterView(AbstractModule module) {
        super(module);
    }

    public RegisterView(AbstractModule module, Object[] args) {
        super(module, args);
        if (args != null && args[0] != null) {
            isEdit = (Boolean) args[0];
        }else{
            isEdit = false;
        }
    }

    @Override
    public ComponentContainer getView() {
        controller = new M001Controller();
        initializeComponents();
        return viewLayout;
    }

    private void initializeComponents() {
        String username = (String) ((WebApplicationContext) module.getApplication().getContext()).getHttpSession().getAttribute("username");
        initializeFormStrings();
        initializeRegisterForm(username);
        initializeDoctorForm();
        initializePharmacistForm();
        createRegisterButton();
        cancelButton = new Button(CANCEL_CAPTION);
        cancelButton.addListener(new Button.ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                if (isEdit) {
                    module.getApplication().getMainWindow().removeWindow(cancelButton.getWindow());
                } else {
                    module.getApplication().changeModule(M001Module.class);
                }
            }
        });

        viewLayout.addComponent(registerForm);
        viewLayout.addComponent(doctorForm);
        viewLayout.addComponent(pharmacistForm);
        HorizontalLayout buttonsFooterLayout = new HorizontalLayout();
        buttonsFooterLayout.setSpacing(true);
        viewLayout.addComponent(buttonsFooterLayout);
        buttonsFooterLayout.addComponent(cancelButton);
        buttonsFooterLayout.addComponent(registerButton);
    }

    private void initializeRegisterForm(String username) {
        registerForm = new Form();

        final FormFieldFactory oldFormFieldFactory = registerForm.getFormFieldFactory();
        registerForm.setFormFieldFactory(new FormFieldFactory() {

            @Override
            public Field createField(Item item, Object propertyId, Component uiContext) {
                Field f = oldFormFieldFactory.createField(item, propertyId, uiContext);
                if (propertyId.equals("username")) {
                    f.setCaption(USERNAME);
                } else if (propertyId.equals("password")) {
                    f.setCaption(PASSWORD);
                } else if (propertyId.equals("type")) {
                    f = createTypeOptionGroup();
                }
                if (f instanceof TextField) {
                    ((TextField) f).setNullRepresentation("");
                }
                f.setRequired(true);
                f.setRequiredError(f.getCaption());
                return f;
            }
        });

        registerForm.setItemDataSource(controller.getRegisterFormBeanItem(username));
        registerForm.setVisibleItemProperties(registerVisibleFields);
    }

    private void initializeDoctorForm() {
        GridLayout gridLayout = new GridLayout(4, 5);
        gridLayout.setSpacing(true);
        doctorForm = new Form(gridLayout);

        final FormFieldFactory oldFormFieldFactory = doctorForm.getFormFieldFactory();
        doctorForm.setFormFieldFactory(new FormFieldFactory() {

            @Override
            public Field createField(Item item, Object propertyId, Component uiContext) {
                Field f = oldFormFieldFactory.createField(item, propertyId, uiContext);
                if (propertyId.equals("firstName")) {
                    f.setCaption(FIRSTNAME_CAPTION);
                } else if (propertyId.equals("surname")) {
                    f.setCaption(SURNAME_CAPTION);
                } else if (propertyId.equals("fatherName")) {
                    f.setCaption(FATHERNAME_CAPTION);
                } else if (propertyId.equals("motherName")) {
                    f.setCaption(MOTHERNAME_CAPTION);
                } else if (propertyId.equals("dateOfBirth")) {
                    f.setCaption(DATEOFBIRTH_CAPTION);
                } else if (propertyId.equals("amka")) {
                    f.setCaption(AMKA_CAPTION);
                } else if (propertyId.equals("ametaa")) {
                    f.setCaption(AMETAA_CAPTION);
                } else if (propertyId.equals("dateAmetaa")) {
                    f.setCaption(DATEAMETAA_CAPTION);
                } else if (propertyId.equals("afm")) {
                    f.setCaption(AFM_CAPTION);
                } else if (propertyId.equals("specialty")) {
                    f.setCaption(SPECIALTY_CAPTION);
                } else if (propertyId.equals("docClub")) {
                    f.setCaption(CLUB_CAPTION);
                } else if (propertyId.equals("licenceNo")) {
                    f.setCaption(LICENCENO_CAPTION);
                } else if (propertyId.equals("phone")) {
                    f.setCaption(PHONE_CAPTION);
                } else if (propertyId.equals("mob")) {
                    f.setCaption(MOB_CAPTION);
                } else if (propertyId.equals("email")) {
                    f.setCaption(EMAIL_CAPTION);
                } else if (propertyId.equals("address")) {
                    f.setCaption(ADDRESS_CAPTION);
                } else if (propertyId.equals("tk")) {
                    f.setCaption(TK_CAPTION);
                } else if (propertyId.equals("city")) {
                    f.setCaption(CITY_CAPTION);
                } else if (propertyId.equals("t004Insurances")) {
                    f = createInsurancesOptionGroup();
                }
                if (f instanceof TextField) {
                    ((TextField) f).setNullRepresentation("");
                }
                f.setRequired(true);
                f.setRequiredError(f.getCaption());
                return f;
            }
        });

        doctorForm.setItemDataSource(controller.getDoctorFormBeanItem(registerForm.getItemDataSource()));
        doctorForm.setVisibleItemProperties(doctorVisibleFields);

        doctorForm.setVisible(true);
    }

    private void initializePharmacistForm() {
        GridLayout gridLayout = new GridLayout(4, 5);
        gridLayout.setSpacing(true);
        pharmacistForm = new Form(gridLayout);

        final FormFieldFactory oldFormFieldFactory = pharmacistForm.getFormFieldFactory();
        pharmacistForm.setFormFieldFactory(new FormFieldFactory() {

            @Override
            public Field createField(Item item, Object propertyId, Component uiContext) {
                Field f = oldFormFieldFactory.createField(item, propertyId, uiContext);
                if (propertyId.equals("firstName")) {
                    f.setCaption(FIRSTNAME_CAPTION);
                } else if (propertyId.equals("surname")) {
                    f.setCaption(SURNAME_CAPTION);
                } else if (propertyId.equals("fatherName")) {
                    f.setCaption(FATHERNAME_CAPTION);
                } else if (propertyId.equals("motherName")) {
                    f.setCaption(MOTHERNAME_CAPTION);
                } else if (propertyId.equals("dateOfBirth")) {
                    f.setCaption(DATEOFBIRTH_CAPTION);
                } else if (propertyId.equals("amka")) {
                    f.setCaption(AMKA_CAPTION);
                } else if (propertyId.equals("ametaa")) {
                    f.setCaption(AMETAA_CAPTION);
                } else if (propertyId.equals("dateAmetaa")) {
                    f.setCaption(DATEAMETAA_CAPTION);
                } else if (propertyId.equals("afm")) {
                    f.setCaption(AFM_CAPTION);
                } else if (propertyId.equals("ampef")) {
                    f.setCaption("ampef");
                } else if (propertyId.equals("mob")) {
                    f.setCaption(MOB_CAPTION);
                } else if (propertyId.equals("licenceNo")) {
                    f.setCaption(LICENCENO_CAPTION);
                } else if (propertyId.equals("pharClub")) {
                    f.setCaption(CLUB_CAPTION);
                } else if (propertyId.equals("pharAddress")) {
                    f.setCaption(ADDRESS_CAPTION);
                } else if (propertyId.equals("pharTk")) {
                    f.setCaption(TK_CAPTION);
                } else if (propertyId.equals("pharCity")) {
                    f.setCaption(CITY_CAPTION);
                } else if (propertyId.equals("pharPhone")) {
                    f.setCaption(PHONE_CAPTION);
                }
                if (f instanceof TextField) {
                    ((TextField) f).setNullRepresentation("");
                }
                f.setRequired(true);
                f.setRequiredError(f.getCaption());
                return f;
            }
        });

        pharmacistForm.setItemDataSource(controller.getPharmacistFormBeanItem(registerForm.getItemDataSource()));
        pharmacistForm.setVisibleItemProperties(pharmacistVisibleFields);

        pharmacistForm.setVisible(false);
    }

    private void initializeFormStrings() {
        registerVisibleFields = new String[]{
                    "username",
                    "password",
                    "type"
                };

        doctorVisibleFields = new String[]{
                    "firstName",
                    "surname",
                    "fatherName",
                    "motherName",
                    "dateOfBirth",
                    "amka",
                    "ametaa",
                    "dateAmetaa",
                    "afm",
                    "specialty",
                    "docClub",
                    "licenceNo",
                    "phone",
                    "mob",
                    "email",
                    "address",
                    "tk",
                    "city",
                    "t004Insurances"
                };

        pharmacistVisibleFields = new String[]{
                    "firstName",
                    "surname",
                    "fatherName",
                    "motherName",
                    "dateOfBirth",
                    "amka",
                    "ametaa",
                    "dateAmetaa",
                    "afm",
                    "ampef",
                    "pharPhone",
                    "mob",
                    "licenceNo",
                    "pharClub",
                    "pharAddress",
                    "pharTk",
                    "pharCity"
                };
    }

    private void createRegisterButton() {
        registerButton = new Button(LoginView.REGISTER_CAPTION);
        registerButton.addListener(new Button.ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                save();
            }
        });
    }

    private void save() {
        try {
            Boolean saveOk = false;
            registerForm.commit();
            if (isDoctor) {
                doctorForm.commit();
                saveOk = controller.registerDoctor(
                        registerForm.getItemDataSource(),
                        doctorForm.getItemDataSource(),
                        (Collection) doctorForm.getField("t004Insurances").getValue());
            } else if (isPharmacist) {
                pharmacistForm.commit();
                saveOk = controller.registerPharmacist(
                        registerForm.getItemDataSource(), pharmacistForm.getItemDataSource());
            }
            if (saveOk) {
                if (isEdit) {
                    module.getApplication().getMainWindow().removeWindow(viewLayout.getWindow());
                } else {
//                    ((WebApplicationContext) module.getApplication().getContext()).getHttpSession().setAttribute("username", registerForm.getField("username").getValue().toString());
//                    Short loginType;
//                    if (isDoctor) {
//                        loginType = LoginView.DOCTOR_TYPE;
//                    } else {
//                        loginType = LoginView.PHARMACIST_TYPE;
//                    }
                    module.getApplication().changeModule(M001Module.class);
                }
                module.getApplication().getMainWindow().showNotification(SIGNUP_CAPTION, Notification.TYPE_HUMANIZED_MESSAGE);

            } else {
                viewLayout.getWindow().showNotification("Η αποθήκευση απέτυχε.", Notification.TYPE_ERROR_MESSAGE);
            }

        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
    }

    private OptionGroup createTypeOptionGroup() {
        OptionGroup optionGroup = new OptionGroup();
        optionGroup.setCaption(TYPE);
//        optionGroup.setRequired(true);
//        optionGroup.setRequiredError(TYPE);
        optionGroup.addItem(LoginView.DOCTOR_TYPE);
        optionGroup.addItem(LoginView.PHARMACIST_TYPE);
//        optionGroup.addItem(LoginView.DEP_TYPE);
        optionGroup.setItemCaption(LoginView.DOCTOR_TYPE, DOCTOR_CAPTION);
        optionGroup.setItemCaption(LoginView.PHARMACIST_TYPE, PHARMACIST_CAPTION);
//        optionGroup.setItemCaption(LoginView.DEP_TYPE, DEP_CAPTION);
        optionGroup.addListener(new ValueChangeListener() {

            @Override
            public void valueChange(ValueChangeEvent event) {
                if (doctorForm != null && pharmacistForm != null) {
                    Short value = (Short) event.getProperty().getValue();
                    if (value.equals(LoginView.DOCTOR_TYPE)) {
                        handleTypeChange(true, false/*, false*/);
                    } else if (value.equals(LoginView.PHARMACIST_TYPE)) {
                        handleTypeChange(false, true/*, false*/);
//                    } else if (value.equals(LoginView.DEP_TYPE)) {
//                        handleTypeChange(false, false, true);
                    }
                }
            }
        });
        optionGroup.setImmediate(true);
        optionGroup.setValue(LoginView.DOCTOR_TYPE);
        return optionGroup;
    }

    private OptionGroup createInsurancesOptionGroup() {
        OptionGroup optionGroup = new OptionGroup(T004INSURANCES_CAPTION, controller.getInsurances());
        optionGroup.setMultiSelect(true);
        return optionGroup;
    }

    private void handleTypeChange(Boolean doctor, Boolean pharmacist/*, Boolean dep*/) {
        isDoctor = doctor;
        isPharmacist = pharmacist;
        /*isDep = dep;*/
        doctorForm.setVisible(doctor);
        pharmacistForm.setVisible(pharmacist);

    }
}
